﻿using FlashPay.DAO.Interface;
using FlashPay.EF;
using FlashPay.EF.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System;
using System.Linq;
using FlashPay.Entity.Parameter;
using FlashPay.Entity;
using System.Linq.Expressions;
using FlashPay.Entity.Response.CardMerchant;
using FlashPay.Util;
using FlashPay.Entity.DAORequest.CardMerchant;
using FlashPay.DAO.Shared;

namespace FlashPay.DAO.Impl
{
    /// <summary>
    /// 卡商数据接口实现
    /// </summary>
    public class CardMerchantDaoImpl : BaseDAO, IDisposable, CardMerchantDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext dbContext { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public CardMerchantDaoImpl(FlashPayContext context)
        {
            dbContext = context;
        }

        public void Dispose()
        {
            if (dbContext != null)
            {
                dbContext.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取卡商
        /// </summary>
        /// <param name="Cmid">编号</param>
        /// <returns>CardMerchant</returns>
        public CardMerchant Get(int Cmid)
        {
            CardMerchant result = dbContext.CardMerchant.Where(x => x.Cmid == Cmid).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="CardMerchant">新增对象</param>
        /// <returns></returns>
        public bool Add(CardMerchant model, out bool isExist)
        {
            bool result = false;
            isExist = false;
            if (!dbContext.CardMerchant.Any(c => c.Cmname == model.Cmname || c.Cmcode == model.Cmcode))
            {
                model.CreateDate = DateTime.Now;
                dbContext.CardMerchant.Add(model);
                if (dbContext.SaveChanges() > 0)
                {
                    result = true;
                }
            }
            else
            {
                isExist = true;
            }
            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns></returns>
        public bool Update(CardMerchant model)
        {
            bool result = false;

            CardMerchant cardMerchant = dbContext.CardMerchant.Find(model.Cmid);

            try
            {
                cardMerchant.CardCommissionerUid = model.CardCommissionerUid;
                cardMerchant.Cmcode = model.Cmcode;
                cardMerchant.Cmcredit = model.Cmcredit;
                cardMerchant.Cmname = model.Cmname;
                //cardMerchant.CardCommissionerUid = model.CardCommissionerUid;
                cardMerchant.DelayRate = model.DelayRate;
                cardMerchant.Remark = model.Remark;
                dbContext.SaveChanges();
                result = true;
            }
            catch {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Cmid">编号</param>
        /// <returns></returns>
        public bool Delete(int Cmid, out bool isUse)
        {
            bool result = false;
            isUse = false;
            CardMerchant cardMerchant = dbContext.CardMerchant.Find(Cmid);

            if (cardMerchant != null)
            {
                if (dbContext.OrderRecord.Any(o => o.Cmid == Cmid))
                {
                    isUse = true;
                }
                else
                {
                    dbContext.CardMerchant.Remove(cardMerchant);
                    if (dbContext.SaveChanges() > 0)
                    {
                        result = true;
                    }
                }
            }
            return result;
        }

        /// <summary>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
        /// 获取所有卡商记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<CardMerchant> GetList(CardMerchantQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<CardMerchant>();

            //卡商名称
            if (!string.IsNullOrEmpty(query.CMName))
            {
                where = where.And(c => c.Cmname == query.CMName);
            }
            //卡商代号
            if (!string.IsNullOrEmpty(query.CMCode))
            {
                where = where.And(c => c.Cmcode == query.CMCode);
            }
            //信用度
            if (!string.IsNullOrEmpty(query.CMCredit))
            {
                where = where.And(c => c.Cmcredit == query.CMCredit);
            }
            //卡管专员ID
            if (query.CardCommissionerUid.HasValue)
            {
                where = where.And(c => c.CardCommissionerUid == query.CardCommissionerUid.Value);
            }
            var list = dbContext.CardMerchant.Where(where.Compile()).ToList();

            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<CardMerchantResponse></returns>
        public PagedList<CardMerchantResponse> GetPager(CardMerchantQuery query)
        {

            var q = from cm in dbContext.CardMerchant
                    join ui in dbContext.UserInfo on cm.CreateUid equals ui.UId
                    join c in dbContext.Company on ui.UCompanyId equals c.CompanyId
                    select new CardMerchantResponse
                    {
                        Cmid = cm.Cmid,
                        CompanyID = c.CompanyId,
                        CardCommissionerUid = cm.CardCommissionerUid,
                        Cmcode = cm.Cmcode,
                        Cmcredit = cm.Cmcredit,
                        Cmname = cm.Cmname,
                        CreateDate = cm.CreateDate,
                        CreateUid = cm.CreateUid,
                        DelayRate = cm.DelayRate,
                        Remark = cm.Remark,
                        //ULoginName = ui.ULoginName
                        ULoginName = dbContext.UserInfo.Where(u => u.UId == cm.CardCommissionerUid).FirstOrDefault().ULoginName
                    };

            //卡商名称
            if (!string.IsNullOrEmpty(query.CMName))
            {
                q = q.Where(c => c.Cmname.Contains(query.CMName));
            }
            //卡商代号
            if (!string.IsNullOrEmpty(query.CMCode))
            {
                q = q.Where(c => c.Cmcode.Contains(query.CMCode));
            }
            //信用度
            if (!string.IsNullOrEmpty(query.CMCredit))
            {
                q = q.Where(c => c.Cmcredit == query.CMCredit);
            }
            //卡管专员
            if (!string.IsNullOrEmpty(query.ULoginName))
            {
                q = q.Where(c => c.ULoginName.Contains(query.ULoginName));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyID));
            }
            //当前登陆用户
            if (query.CreateUid>0)
            {
                q = q.Where(c => c.CreateUid==query.CreateUid);
            }

            var row = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();
            var count = q.Count();

            return new PagedList<CardMerchantResponse>
            {
                TData = row,
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = count,
                Success = true
            };
        }

        public void Get(BaseModel<List<CardMerchant>> result, CardMerchantRequest model)
        {
            /* 呼叫資料庫 */
            IQueryable<CardMerchant> _result = dbContext.CardMerchant.Where(
                card =>
                  (model.CMName == null || card.Cmname.Contains(model.CMName)
                  )
            );
            List<CardMerchant> list = Split(_result, result.PageIndex, result.PageSize);
            Int32 totalCount = _result.Count();

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = totalCount;
            result.Result = list;
        }

        public void Get2(BaseModel<List<CardMerchant>> result, CardMerchantRequest model)
        {
            /* 呼叫資料庫 */
            IQueryable<CardMerchant> _result = dbContext.CardMerchant.Where(
                card =>(model.CMID == null || model.CMID.Count == 0 || model.CMID.Contains(card.Cmid)));
            List<CardMerchant> list = Split(_result, result.PageIndex, result.PageSize);
            Int32 totalCount = _result.Count();

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = totalCount;
            result.Result = list;
        }

        /// <summary>
        /// 通过条件获取卡商信息
        /// </summary>
        /// <param name="SearchValue">搜索值</param>
        /// <param name="SearchType">值类型</param>
        /// <returns>List<CardMerchant></returns>
        public List<CardMerchantResponse> SearchCardMerchant(CardMerchantQuery query)
        {
            var q = from cm in dbContext.CardMerchant
                    join ui in dbContext.UserInfo on cm.CreateUid equals ui.UId
                    select new CardMerchantResponse
                    {
                        Cmid = cm.Cmid,
                        CompanyID = ui.UCompanyId,
                        CardCommissionerUid = cm.CardCommissionerUid,
                        Cmcode = cm.Cmcode,
                        Cmcredit = cm.Cmcredit,
                        Cmname = cm.Cmname,
                        CreateDate = cm.CreateDate,
                        CreateUid = cm.CreateUid,
                        DelayRate = cm.DelayRate,
                        Remark = cm.Remark,
                        ULoginName = ui.ULoginName
                    };
            //卡商名称
            if (!string.IsNullOrEmpty(query.CMName))
            {
                q = q.Where(c => c.Cmname.Contains(query.CMName));
            }
            //卡商代号
            if (!string.IsNullOrEmpty(query.CMCode))
            {
                q = q.Where(c => c.Cmcode.Contains(query.CMCode));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyID));
            }

            return q.ToList();
        }
    }
}
